package com.hrsystem.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hrsystem.entity.Employee;
import com.hrsystem.entity.SalaryList;
import com.hrsystem.entity.SalaryListDetail;
import com.hrsystem.lang.Result;
import com.hrsystem.mapper.EmployeeMapper;
import com.hrsystem.service.EmployeeService;
import com.hrsystem.service.SalaryListDetailService;
import com.hrsystem.service.SalaryListService;
import com.hrsystem.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;



@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    @Resource
    EmployeeMapper employeeMapper;

    @Autowired
    SalaryListDetailService salaryListDetailService;

    @Autowired
    SalaryListService salaryListService;


    @PostMapping("/add/picture")
    public String coversUpload(MultipartFile file) throws Exception {
        String folder = "C:/Users/Alf乂/Desktop/a/";
        File imageFolder = new File(folder);
        File f = new File(imageFolder, StringUtils.getRandomString(6) + file.getOriginalFilename()
                .substring(file.getOriginalFilename().length() - 4));
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        try {
            file.transferTo(f);
            String imgURL = "http://localhost:8080/api/file/" + f.getName();
            return imgURL;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }




    @Transactional
    @PostMapping("/add")
    public Result add(@RequestBody Employee employee){
        Employee temp;
        temp = new Employee();
        temp.setCreateFileTime(LocalDate.now());
        temp.setReviewer(null);
        temp.setReviewerTime(null);
        temp.setIsReview(false);
        BeanUtil.copyProperties(employee, temp, "FileId", "CreateFileTime","IsReview");
        System.out.println(employee);
        System.out.println(1);
        employeeService.saveOrUpdate(temp);
        return Result.success(null);
    }

    @Transactional
    @GetMapping("/reviewSelectBriefly")
    public Result reviewSelectBriefly(){
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isDelete",false);
        queryWrapper.eq("isReview",false);
        queryWrapper.select("File_id","name","gender","fOrg_id","sOrg_id","tOrg_id","nJob_id");
        List<Employee> selectEmployeeList = employeeMapper.selectList(queryWrapper);
        return Result.success(selectEmployeeList);
    }

    @Transactional
    @GetMapping("/recoverySelectBriefly")
    public Result recoverySelectBriefly(){
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isDelete",true);
        queryWrapper.eq("isReview",false);
        queryWrapper.select("File_id","name","gender","fOrg_id","sOrg_id","tOrg_id","nJob_id");
        List<Employee> selectEmployeeList = employeeMapper.selectList(queryWrapper);
        return Result.success(selectEmployeeList);
    }

    @Transactional
    @GetMapping("/selectBriefly")
    public Result selectBriefly(){
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isReview",true);
        queryWrapper.eq("isDelete",false);
        queryWrapper.select("File_id","name","gender","fOrg_id","sOrg_id","tOrg_id","nJob_id");
        List<Employee> selectEmployeeList = employeeMapper.selectList(queryWrapper);
        return Result.success(selectEmployeeList);
    }

    @Transactional
    @GetMapping("/ReviewDetail/{id}")
    public Result detail(@PathVariable(name = "id") Long id){
        Employee employee = employeeService.getById(id);
        return Result.success(employee);
    }

    @Transactional
    @GetMapping("/ChangeDetail/{id}")
    public Result changeDetail(@PathVariable(name = "id") Long id){
        Employee employee = employeeService.getById(id);
        //TODO 要加一个Assert.notNull（employee,"该档案已经删除'）非空断言检测，等Shiro引入后再加
        return Result.success(employee);
    }

    @Transactional
    @PostMapping("/reviewFile")
    public Result reviewFile(@RequestBody Employee employee) {
        Employee temp;
        temp = new Employee();
        temp.setReviewerTime(LocalDate.now());
        temp.setIsReview(true);
        BeanUtil.copyProperties(employee, temp, "reviewerTime", "IsReview");
        employeeService.saveOrUpdate(temp);
        return Result.success(null);
    }

    @Transactional
    @PostMapping("/changeFile")
    public Result changeFile(@RequestBody Employee employee) {
        SalaryListDetail salaryListDetail=salaryListDetailService.getByFileId(employee.getFileId());
        salaryListDetailService.removeById(salaryListDetailService.getByFileId(employee.getFileId()).getSListDetailId());
        SalaryList salaryList = new SalaryList();
        salaryList.setSListId(salaryListDetail.getSListId());
        salaryList=salaryListService.getById(salaryList.getSListId());
        if(salaryList.getNumber()==1){
            salaryListService.removeById(salaryList.getSListId());
        }else{
            salaryList.setNumber(salaryList.getNumber()-1);
            salaryListService.saveOrUpdate(salaryList);
        }

        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("File_id", employee.getFileId());
        Employee employeeNow = employeeMapper.selectOne(queryWrapper);
        if (Objects.equals(employee.getVersion(), employeeNow.getVersion())){
            Employee temp;
            temp = new Employee();
            temp.setIsReview(false);
            BeanUtil.copyProperties(employee, temp);
            Long nowVersion = temp.getVersion();
            if (nowVersion == null) {
                // 如果version为null，设置一个默认值，例如0
                nowVersion = 0L;
            }
            Long newVersion = nowVersion + 1;
            temp.setVersion(newVersion);
            employeeService.saveOrUpdate(temp);
            return Result.success(null);
        }else {
            return Result.success("修改失败");
        }
    }

    @Transactional
    @PostMapping("/deleteFile/{id}")
    public Result deleteFile(@PathVariable(name = "id") Long id){
        salaryListDetailService.removeById(salaryListDetailService.getByFileId(id).getSListDetailId());
        Employee employee = employeeService.getById(id);
        employee.setIsDelete(true);
        employee.setIsReview(false);
        employeeService.saveOrUpdate(employee);
        return Result.success(null);
    }

    @Transactional
    @PostMapping("/recoveryFile/{id}")
    public Result recoveryFile(@PathVariable(name = "id") Long id){
        Employee employee = employeeService.getById(id);
        employee.setIsDelete(false);
        employee.setIsReview(false);
        employeeService.saveOrUpdate(employee);
        return Result.success(null);
    }

    @Transactional
    @GetMapping("/queryFile/{forgId}/{sorgId}/{torgId}/{cjobId}/{njobId}/{creatTimeStart}/{creatTimeEnd}")
    public Result queryFile(@PathVariable(name = "forgId") String forgId, @PathVariable(name = "sorgId") String sorgId, @PathVariable(name = "torgId") String torgId, @PathVariable(name = "cjobId") String cjobId, @PathVariable(name = "njobId") String njobId, @PathVariable(name = "creatTimeStart") String creatTimeStart, @PathVariable(name = "creatTimeEnd") String  creatTimeEnd) throws ParseException {
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (!forgId.equals("请选择")) {
            queryWrapper.eq("fOrg_id", Long.parseLong(forgId));
        }
        if (!sorgId.equals("请选择") && !sorgId.equals("empty")) {
            queryWrapper.eq("sOrg_id", Long.parseLong(sorgId));
        }
        if (!torgId.equals("请选择") && !torgId.equals("empty")) {
            queryWrapper.eq("tOrg_id", Long.parseLong(torgId));
        }
        if (!cjobId.equals("请选择")) {
            queryWrapper.eq("cJob_id", Long.parseLong(cjobId));
        }
        if (!njobId.equals("请选择") && !njobId.equals("empty")){
            queryWrapper.eq("nJob_id", Long.parseLong(njobId));
        }
        if (!creatTimeStart.equals("undefined") && !creatTimeEnd.equals("undefined")){
            Date creatTimeStartDate = simpleDateFormat.parse(creatTimeStart);
            Date creatTimeEndDate = simpleDateFormat.parse(creatTimeEnd);
            queryWrapper.between("CreateFileTime", creatTimeStartDate ,creatTimeEndDate);
        }
        queryWrapper.eq("isDelete",false);
        queryWrapper.eq("isReview",true);
        queryWrapper.select("File_id","name","gender","fOrg_id","sOrg_id","tOrg_id","nJob_id");
        List<Employee> queryEmployeeFile = employeeMapper.selectList(queryWrapper);
        return Result.success(queryEmployeeFile);
    }

}
